//
//  APNSManager.m
//  YoucApp
//
//  Created by Liam on 12/2/12.
//
//

#import "APNSManager.h"
#import "UserManager.h"
#import "YoucApi.h"
#import "YAReqPutDeviceToken.h"
#import "YAReqSetDND.h"

@implementation APNSManager

OBJC_IMPL_SINGLETON(APNSManager);

- (void)openAPNS
{
	if (![NSThread isMainThread])
	{
		[self performSelectorOnMainThread:@selector(openAPNS) withObject:nil waitUntilDone:NO];
		return;
	}
	
	BOOL bSound = [[NSUserDefaults standardUserDefaults] boolForKey:@"an_type_sound"];
	
	[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
											UIRemoteNotificationTypeAlert |
											UIRemoteNotificationTypeBadge |
											(bSound ? UIRemoteNotificationTypeSound : UIRemoteNotificationTypeNone)];
}

- (void)APNSDeviceTokenSet:(NSString *)deviceToken
{
	YAReqPutDeviceToken *reqPutDeviceToken = [[[YAReqPutDeviceToken alloc] init] autorelease];
	
	[[UserManager instance] fillObjectWithSession:reqPutDeviceToken];
	reqPutDeviceToken.deviceToken = deviceToken;
	
	[[YoucApi instance] userPutDeviceToken:reqPutDeviceToken];
}

- (BOOL)isAPNSOpened:(BOOL *)pSoundOpened
{
	UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
	
	if (pSoundOpened)
	{
		*pSoundOpened = (type & UIRemoteNotificationTypeSound) == UIRemoteNotificationTypeSound;
	}
	
	return (type != UIRemoteNotificationTypeNone);
}

- (void)setDND:(BOOL)isDND nightDND:(BOOL)nightDND
{
	YAReqSetDND *reqSetDND = [[[YAReqSetDND alloc] init] autorelease];
	
	[[UserManager instance] fillObjectWithSession:reqSetDND];
	reqSetDND.dndState = isDND ? DNDState_Opened : DNDState_Closed;
	reqSetDND.dndType = nightDND ? DNDType_Night : DNDType_All;
	
	[[YoucApi instance] userSetDND:reqSetDND];
}

@end
